package org.Niu;

import java.util.concurrent.atomic.AtomicInteger;

public class VolatileAtomicDemo {
    //private volatile int count = 0;
    //1. 可见性
    //2. 禁止指令重排序
    //3. 不保证原子性


    private AtomicInteger count = new AtomicInteger(0);

    public void increment() {count.incrementAndGet(); // 不是原子操作（读 + 修改 + 写）
         }

    public static void main(String[] args) throws InterruptedException {
//        VolatileAtomicDemo demo = new VolatileAtomicDemo();
        var demo = new VolatileAtomicDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    demo.increment();
                }
            }).start();
        }
        Thread.sleep(2000);
        System.out.println(demo.count); // 可能小于 10000
    }
}